package gui.core.model;

import java.util.ArrayList;
import java.util.Collection;

import javax.swing.ListModel;
import javax.swing.event.ListDataListener;

import model.Student;
import model.StudentService;
import model.StudentServiceListener;
import model.impl.StudentImpl;

public class StudentListModel implements ListModel<Student>, StudentServiceListener
{
	StudentService _service;
	Collection<Student> _students;
	Collection<ListDataListener> _dataListeners;
	
	public StudentListModel(StudentService service)
	{
		_service = service;
		_dataListeners = new ArrayList<ListDataListener>();
	}
	
	@Override
	public void addListDataListener(ListDataListener l)
	{
		// TODO Auto-generated method stub
		_dataListeners.add(l);
		
	}

	@Override
	public Student getElementAt(int index)
	{
		// TODO Auto-generated method stub
		System.out.println("called getElementAt " + index);
		return (Student)(_students.toArray())[index];
	}

	@Override
	public int getSize()
	{
		// TODO Auto-generated method stub
		return _students != null ? _students.size() : 0;
	}

	@Override
	public void removeListDataListener(ListDataListener l)
	{
		// TODO Auto-generated method stub
		_dataListeners.remove(l);
	}
	
	@Override
	public void onStudentsChanged(Collection<Student> added,
			Collection<Student> removed)
	{
		// TODO Auto-generated method stub
		if( added.size() > 0 && removed.size() == 0 )
		{
			_students = added;
		}
		else if( added.size() == 1 && removed.size() == 1 )
		{
			// student updated
		}
		else if( added.size() == 0 && removed.size() > 0 )
		{
			
		}
		
		notifyDataChanged();
		
	}
	
	private void notifyDataChanged()
	{
		for( ListDataListener l : _dataListeners )
		{
			l.contentsChanged(null);
		}
	}
	
}
